package com.gyt.manager.common.utils;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.dozer.DozerBeanMapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.TypeMappingOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
 * <p>
 * 1. 持有Mapper的单例.
 * 2. 返回值类型转换.
 * 3. 批量转换Collection中的所有对象.
 * 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
 *
 * @author v_yantgao
 */
public class BeanUtil {

    private static final Logger log = LoggerFactory.getLogger(BeanUtil.class);
    /**
     * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

//    private static Mapper dozer = DozerBeanMapperBuilder.create().withMappingFiles("config/bean/userMapping.xml").build();

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        if (source == null) {
            return null;
        }
        return dozer.map(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static <T> List<T> mapList(Collection<?> sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        if (sourceList == null) {
            return destinationList;
        }
        for (Object source : sourceList) {
            T destinationObject = dozer.map(source, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * 全属性复制
     *
     * @param source            源对象
     * @param destinationObject 输出对象
     */
    public static void copy(final Object source, final Object destinationObject) {
        if (null == source || null == destinationObject) {
            return;
        }
        dozer.map(source, destinationObject);
    }

    /**
     * 忽略null值的属性复制
     *
     * @param source            源对象
     * @param destinationObject 输出对象
     */
    public static void copyProperties(final Object source, final Object destinationObject) {
        // 自定义配置是全局DozerBeanMapper有效的 并且设定配置必须在map()前 所以这里不使用单例的dozer
        DozerBeanMapper dozer = new DozerBeanMapper();
        dozer.addMapping(new BeanMappingBuilder() {
            @Override
            protected void configure() {
                mapping(source.getClass(), destinationObject.getClass(), mappingBuilder -> {
                    mappingBuilder.mapNull(false);
                    // mappingBuilder.mapEmptyString(false);
                });
            }
        });
        dozer.map(source, destinationObject);
        dozer.destroy();
    }

    /**
     * 自定义配置复制
     *
     * @param source            源对象
     * @param destinationObject 输出对象
     */
    public static void copyProperties(final Object source, final Object destinationObject, TypeMappingOption... typeMappingOption) {
        // 自定义配置是全局DozerBeanMapper有效的 并且设定配置必须在map()前 所以这里不使用单例的dozer
        DozerBeanMapper dozer = new DozerBeanMapper();
        dozer.addMapping(new BeanMappingBuilder() {
            @Override
            protected void configure() {
                mapping(source.getClass(), destinationObject.getClass(), typeMappingOption);
            }
        });
        dozer.map(source, destinationObject);
        dozer.destroy();
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        int setCoutn = 0;
        T obj = null;
        try {
            obj = beanClass.newInstance();
            Field[] fields = getClassFields(obj.getClass());
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
                setCoutn++;
            }
        } catch (InstantiationException | IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
        return 0 == setCoutn ? null : obj;
    }

    @SuppressWarnings("rawtypes")
    private static Field[] getClassFields(Class curClass) {
        Field[] objFields = curClass.getDeclaredFields();
        if (curClass.getSuperclass() != null) {
            objFields = ArrayUtils.addAll(objFields, getClassFields(curClass.getSuperclass()));
        }
        return objFields;
    }

}